#include "ota_http.h"

static size_t recv_callback(void *contents, size_t size, size_t nmemb, void *userp)
{
    // 将接收到的数据写入文件
    char *data = (char *)contents;
    size_t len = size * nmemb;
    char *json = (char *)userp;
    memcpy(json, data, len);
    json[len] = '\0';
    
    return len;
}

char *ota_http_getJson(char *url)
{
    // 创建一个CURL句柄
    CURL *curl = curl_easy_init();
    // 设置URL
    curl_easy_setopt(curl, CURLOPT_URL, url);
    // 设置接收响应的回调
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, recv_callback);
    // 设置回调的参数
    char *json = (char *)malloc(1024);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, json);
    // 发送请求
    CURLcode status = curl_easy_perform(curl);
    if (status != CURLE_OK)
    {
        printf("请求失败: %s\n", curl_easy_strerror(status));
        // 释放内存
        curl_easy_cleanup(curl);
        free(json);
        return NULL;
    }
    return json;
}

int ota_http_dowload(char *url, char *filename)
{
    // 创建一个CURL句柄
    CURL *curl = curl_easy_init();
    // 设置URL
    curl_easy_setopt(curl, CURLOPT_URL, url);
    // 设置接收响应的回调
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);
    // 设置回调的参数
    FILE *fp = fopen(filename, "wb");
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
    // 发送请求
    CURLcode status = curl_easy_perform(curl);
    if (status != CURLE_OK)
    {
        printf("请求失败: %s\n", curl_easy_strerror(status));
        // 释放内存
        curl_easy_cleanup(curl);
        fclose(fp);
        return -1;
    }
    curl_easy_cleanup(curl);
    fclose(fp);
    return 0;
}
